package com.pig4cloud.pig.homecenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.homecenter.entity.HassEntityRegistryEntity;
import com.pig4cloud.pig.homecenter.service.HassEntityRegistryService;
import com.pig4cloud.pig.homecenter.util.DateTimeUtils;
import com.pig4cloud.pig.homecenter.vo.SyncStateVO;
import com.pig4cloud.pig.homecenter.ws.HassWebsocketMessageUtils;
import com.pig4cloud.plugin.websocket.config.WebSocketMessageSender;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;

@Slf4j
@RequiredArgsConstructor
@RestController
@Tag(description = "biz", name = "业务模块")
@RequestMapping("/biz/ws/hass")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class BizHassController {

	private final HassEntityRegistryService hassEntityRegistryService;

	@Operation(summary = "测试通信", description = "接收http发送websocket")
	@PostMapping("/testMessage")
	public R testMessage(@RequestBody JSONObject params) {
		HassWebsocketMessageUtils.sendHassMessage(params.toJSONString());
		return R.ok();
	}

	@Operation(summary = "接收消息", description = "接收hass中websocket返回的消息")
	@PostMapping("/receiveMessage")
	public R receiveMessage(@RequestBody JSONObject params) {
		System.out.println(params.toJSONString());
		return R.ok();
	}

	@Operation(summary = "接收事件", description = "接收hass推送的事件")
	@PostMapping("/receiveEvent")
	public R receiveEvent(@RequestBody JSONObject params) {
		String type = params.getString("type");
		if(!"event".equals(type)){
			return R.failed("非事件消息");
		}
		JSONObject event = params.getJSONObject("event");
		JSONObject data = event.getJSONObject("data");
		String timeStr = event.getString("time_fired");
		Timestamp timeFired = DateTimeUtils.hassTimeToTimestamp(timeStr);
		String entityId = data.getString("entity_id");
		JSONObject newState = data.getJSONObject("new_state");
		String state = String.valueOf(newState.get("state"));

		QueryWrapper<HassEntityRegistryEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(HassEntityRegistryEntity::getEntityId, entityId)
				.eq(HassEntityRegistryEntity::getUserId, SecurityUtils.getUser().getId());
		queryWrapper.lambda().lt(HassEntityRegistryEntity::getStateUpdateTime,timeFired);
		HassEntityRegistryEntity entity = hassEntityRegistryService.getOne(queryWrapper,false);
		if(entity != null){
			entity.setState(state);
			entity.setStateUpdateTime(timeFired);
			hassEntityRegistryService.updateById(entity);
			params.put("messageSource","hass");
			HassWebsocketMessageUtils.sendWebMessage(params.toJSONString());
		}else{
			log.info("未找到对应的实体:{}",entityId);
		}

		return R.ok();
	}

	@Operation(summary = "状态同步", description = "状态同步")
	@PostMapping("/syncState")
	public R syncState(@RequestBody SyncStateVO vo) {
		if(vo.getSuccess()){
			vo.getResult().forEach(item -> {
				QueryWrapper<HassEntityRegistryEntity> queryWrapper = new QueryWrapper<>();
				queryWrapper.lambda().eq(HassEntityRegistryEntity::getEntityId, item.getEntityId())
						.eq(HassEntityRegistryEntity::getUserId, SecurityUtils.getUser().getId());
				HassEntityRegistryEntity entity = hassEntityRegistryService.getOne(queryWrapper,false);
				if(entity != null){
					entity.setState(item.getState());
					entity.setStateUpdateTime(DateTimeUtils.now());
					entity.setAttributes(item.getAttributes());
					hassEntityRegistryService.updateById(entity);
				}else{
					log.info("未找到对应的实体:{}",item.getEntityId());
				}
			});
		}
		return R.ok();
	}
}
